/*
 * @Author: Otway
 * @Date: 2019-01-09 11:16:08
 * @LastEditors: Otway
 * @LastEditTime: 2019-08-30 18:50:09
 * @copyright: h-visions
 */
import React, { PureComponent } from 'react';
import { BasicPagination, isInvalidObject, compareNum, TableCustomize, openSuccessModal, openModalMessage, compareString } from '../../../components/TableCustomize'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
// import * as CheckManagementService from '../../../axios/CheckManagement'
import { withRouter } from 'react-router';
import { Row, Col, Form, Select, Layout, Upload, Button, InputNumber, Table, Input, Alert, Spin, Modal, Drawer, Divider, Icon, Badge, PageHeader, Tabs, Card } from 'antd';
import { getBase64 } from '../../../utils/action'
import InfoForm from './Components/InfoForm'
import ResultForm from './Components/ResultForm';
import EditTable from './Components/EditTable';
const FormItem = Form.Item;
const { Header, Footer, Sider, Content } = Layout;
const { Option } = Select



class SubPage1 extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            spinning: false,
            formData1: {},
            searchItemFather: {},
            infoForm: {},
            resultForm: {},
            columns: [
                {
                    title: '序号',
                    dataIndex: 'dataIndex',
                    width: 100,
                    render: (text, record, index) => <span>{index + 1}</span>
                },
                {
                    title: '测量点',
                    dataIndex: 'batchNo',
                    width: 100,
                    sorter: (a, b) => compareString(a.batchNo, b.batchNo)
                },

                {
                    title: '最小标准值',
                    width: 100,
                    dataIndex: 'model',
                    sorter: (a, b) => compareNum(a.model, b.model),
                    // editable: true
                },
                {
                    title: '最大标准值',
                    width: 100,
                    // allowEllipsis: true,
                    dataIndex: 'department',
                    sorter: (a, b) => compareNum(a.department, b.department)
                },
                {
                    title: '单位',
                    width: 100,
                    // allowEllipsis: true,
                    dataIndex: 'assembleProcess',
                    sorter: (a, b) => compareString(a.assembleProcess, b.assembleProcess)
                },
                {
                    title: '实测数据-A项',
                    width: 100,
                    editable: true,
                    dataIndex: 'testMachineProcess',
                },
                {
                    title: '实测数据-B项',
                    width: 200,
                    editable: true,
                    dataIndex: 'qualityCheckProcess',
                },
                // {
                //   title: '操作',
                //   width: 150,
                //   dataIndex: 'opts',
                //   render: (text, record) => <>
                //     <a onClick={() => this.create(1, record)}>分配</a>
                //   </>
                // }
            ],
            isEdit: false,   // true 可编辑  false 不可编辑
            previewVisible: false,
            previewImage: '',
            fileList: [
                {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                },
                {
                    uid: '-2',
                    name: 'image.png',
                    status: 'done',
                    url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                },
                {
                    uid: '-3',
                    name: 'image.png',
                    status: 'done',
                    url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                },
                {
                    uid: '-4',
                    name: 'image.png',
                    status: 'done',
                    url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                },
                {
                    uid: '-5',
                    name: 'image.png',
                    status: 'error',
                },
            ],
            dataSource1: [],
            dataSource2: [],
        }
    }
    componentDidMount() {

        console.log(this.props.location)
        this.setState({ searchItemFather: this.props.location.data ? this.props.location.data.searchItem : JSON.parse(localStorage.getItem('ProcessQuality_searchItem')) }, this.fetch)


        let dataSource1 = [{
            'batchNo': '111',
            'model': '111',
            'department': '111',
            'assembleProcess': '111',
            'testMachineProcess': '1',
            'qualityCheckProcess': '11',
        }, {
            'batchNo': '222',
            'model': '222',
            'department': '222',
            'assembleProcess': '222',
            'testMachineProcess': '',
            'qualityCheckProcess': '',
        }, {
            'batchNo': '333',
            'model': '333',
            'department': '333',
            'assembleProcess': '333',
            'testMachineProcess': '',
            'qualityCheckProcess': '',
        }]
        let dataSource2 = [{
            'batchNo': 'aaa',
            'model': 'aaa',
            'department': 'aaa',
            'assembleProcess': 'aaa',
            'testMachineProcess': '',
            'qualityCheckProcess': '',
        }, {
            'batchNo': 'bbb',
            'model': 'bbb',
            'department': 'bbb',
            'assembleProcess': 'bbb',
            'testMachineProcess': '',
            'qualityCheckProcess': '',
        }]

        this.setState({ dataSource1, dataSource2 })
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    fetch = (pageNum = 1, pageSize = 100) => {
        this.setState({ loading: true })
        const { resultForm, infoForm } = this.state
        // searchItem.pageNum = pageNum
        // searchItem.pageSize = pageSize

        // this.setState({ spinning: true })
        // CheckManagementService.findCheckTemplate(searchItem).then(res => {
        //     // console.log(res.data.data, '查询试机模板');
        //     if (res.data.code !== 200) {
        //         openModalMessage('warning', res.data.msg);
        //         return;
        //     }
        //     this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize });
        // }).catch(err => {
        //     openModalMessage('error', err.message);
        // })
    }
    handleSearch = () => {
        // this.resultForm   infoForm   resultForm
        this.infoForm.validateFields((err, value) => {
            if (err) return;
            console.log(value);
            if (value.assembleStartDate && value.assembleStartDate.length === 2) {
                value.firstOutputDateMin = value.assembleStartDate[0].format('YYYY-MM-DD 00:00:00')
                value.firstOutputDateMax = value.assembleStartDate[1].format('YYYY-MM-DD 23:59:59')
                delete (value.assembleStartDate)
            }
            this.setState({ searchItem: value }, this.fetch);
        })
    };
    edit = () => {
        console.log('编辑');
        this.setState({ isEdit: true })
    }
    getTableData = (data, row) => {
        for (let key in row) {
            let arr = key.split('_')
            const index = data.findIndex(item => {
                return arr[1] === item.batchNo
            });
            if (index > -1) {
                const item = data[index];
                data.splice(index, 1, {
                    ...item,
                    [arr[0]]: row[key],
                });
            } else {
                data.push(row);
            }
        }
        return data
    }
    save = () => {
        console.log('保存');
        // 获取 表格1 数据
        this.editTable1.validateFields((error, row) => {
            if (error) {
                return;
            }
            console.log(row, 'editTable1');
            const newData1 = [...this.state.dataSource1];
            this.setState({ dataSource1: this.getTableData(newData1, row) });
        });
        // 获取 表格2 数据
        this.editTable2.validateFields((error, row) => {
            if (error) {
                return;
            }
            console.log(row, 'editTable2');
            const newData2 = [...this.state.dataSource2];
            this.setState({ dataSource2: this.getTableData(newData2, row) });
        });
        // 获取基础信息
        this.infoForm.validateFields((error, value) => {
            if (error) {
                return;
            }
            console.log(value, '获取基础信息');
        });
        // 获取结论信息
        this.resultForm.validateFields((error, value) => {
            if (error) {
                return;
            }
            console.log(value, '获取结论信息');
        });
        this.setState({ isEdit: false })
    }

    saveFileList = (index, value) => {
        const { fileList } = this.state;
        fileList[index] = value;
        this.setState({ ...fileList })
        console.log(fileList)
    }
    handleCancel = () => {
        this.setState({
            previewVisible: false,
            isEdit: false
        })
    }

    // 预览
    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
        });
    };

    render() {
        const { form: { getFieldDecorator } } = this.props;
        const { fileList, previewVisible, previewImage, searchItemFather, infoForm, resultForm, columns, isEdit, dataSource1, dataSource2 } = this.state
        const _this = this
        const titleStyle = { fontWeight: 'bold', fontSize: 14 }

        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        const propsFile = {
            accept: '.png,.gif,.jpg,.jpeg',
            listType: "picture-card",
            onPreview: this.handlePreview,
            onRemove: (file) => {
                this.setState((state) => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    // _this.saveFileList(0, newFileList)
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: (file) => {
                // _this.saveFileList(0, [...fileList, file])
                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));
                return false;
            },
            fileList,
        };

        return (
            <div>
                <BasicLayoutSearch>
                    <PageHeader
                        style={{ padding: '4px 24px' }}
                        onBack={() => this.props.history.push({ pathname: '/ProcessQuality', data: searchItemFather })}
                        title={`机架水平精度调校记录`}>
                    </PageHeader>
                </BasicLayoutSearch>
                <Layout className="layout-model">
                    <InfoForm
                        titleStyle={titleStyle}
                        title='基础信息'
                        searchItem={infoForm}
                        isEdit={isEdit}
                        ref={node => (this.infoForm = node)}
                    />
                </Layout>
                <Layout className="layout-model">
                    <Card title={<div style={titleStyle}>图片</div>} bordered={false}>
                        <Upload {...propsFile}>
                            {isEdit ? uploadButton : ''}
                        </Upload>
                        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                    </Card>
                </Layout>
                <Layout className="layout-model">
                    <EditTable
                        isEdit={isEdit}
                        dataSource={dataSource1}
                        columns={columns}
                        allowDrafting={true}
                        allowRowEdit={true}
                        allowEditable={true}
                        ref={node => (this.editTable1 = node)}
                        rowKey={(record) => record.batchNo}
                    />
                </Layout>
                <Layout className="layout-model">
                    <EditTable
                        isEdit={isEdit}
                        dataSource={dataSource2}
                        columns={columns}
                        allowDrafting={true}
                        allowRowEdit={true}
                        allowEditable={true}
                        ref={node => (this.editTable2 = node)}
                        rowKey={(record) => record.batchNo}
                    />
                </Layout>
                <Layout className="layout-model">
                    <ResultForm
                        titleStyle={titleStyle}
                        title='结论信息'
                        searchItem={resultForm}
                        isEdit={isEdit}
                        ref={node => (this.resultForm = node)}
                    />
                </Layout>

                <Layout className="layout-model" >
                    {
                        isEdit ? null : <div style={{ display: 'flex', justifyContent: 'end' }}><Button type='primary' onClick={this.edit} style={{ width: 65 }}>编辑</Button></div>
                    }
                    {
                        isEdit ?
                            <div style={{ display: 'flex', justifyContent: 'end' }}>
                                <Button type='default' onClick={this.handleCancel} style={{ width: 65 }}>取消</Button>&emsp;
                                <Button type='primary' onClick={this.save} style={{ width: 65 }}>保存</Button>
                            </div>
                            : null
                    }
                </Layout>
            </div>
        );
    }
}
export default Form.create()(withRouter(SubPage1));